package com.itheima.travel.service.impl;

import com.itheima.travel.mapper.UserMapper;
import com.itheima.travel.pojo.User;
import com.itheima.travel.pojo.UserExample;
import com.itheima.travel.req.UserVo;
import com.itheima.travel.service.UserService;
import com.itheima.travel.utils.BeanConv;
import com.itheima.travel.utils.EmptyUtil;
import com.itheima.travel.utils.MD5Coder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private HttpSession session;

    /**
     * 用户注册
     * @param userVo
     * @return
     */
    @Override
    public Boolean registerUser(UserVo userVo) {
        //转换VO
        User user = BeanConv.toBean(userVo, User.class);
        user.setPassword(MD5Coder.md5Encode(user.getPassword()));
        //用户注册
        int i = userMapper.insert(user);
        return i > 0;
    }

    /**
     * 用户登录
     * @param userVo
     * @return
     */
    @Override
    public UserVo loginUser(UserVo userVo) {
        //组装条件
        UserExample example = new UserExample();
        example.createCriteria()
                .andUsernameEqualTo(userVo.getUsername())
                .andPasswordEqualTo(MD5Coder.md5Encode(userVo.getPassword()));
        //查询list结果集
        List<User> list = userMapper.selectByExample(example);
        UserVo resultUserVo = null;
        //判断结果
        if (!EmptyUtil.isNullOrEmpty(list)) {
            User user = list.get(0);
            //转换VO
            resultUserVo = BeanConv.toBean(user, UserVo.class);
            //放入会话
            session.setAttribute(session.getId(), resultUserVo);
        }
        return resultUserVo;
    }

    /**
     * 用户退出
     */
    @Override
    public void loginOutUser() {
        //销毁session
        //session.invalidate();
        //从会话中删除当前对象
        session.removeAttribute(session.getId());
    }

    /**
     * 判断用户是否登录
     * @return
     */
    @Override
    public Boolean isLogin() {
        //根据当前用户是否存在判断登录状态
        Object user = session.getAttribute(session.getId());
        return !EmptyUtil.isNullOrEmpty(user);
    }
}
